package com.thesis.downloader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import com.thesis.utils.AllBusStop;
import com.thesis.utils.BusStop;
import com.thesis.utils.CoordinateConversion;

public class BusInfoDownloader {
	private final String URL_BUSMAP = "http://map.ebms.vn/routeoftrunk.aspx";
	private final String TAG_STARTLIST = "<select name=\"lstTuyen\" id=\"lstTuyen\">";
	private final String TAG_ENDLIST = "</select>";

	private final String FOLDERNAME = "bus/";

	private final String allBusStop_filename = FOLDERNAME + "allBusStop.txt";
	private final String allBusRoute_filename = FOLDERNAME + "allBusRoute.txt";
	private final String allBusStop_binfilename = FOLDERNAME + "allBusStop.bin";
	private final String allBusRoute_binfilename = FOLDERNAME + "allBusRoute.bin";

	private int maxBusStopID = 0;

	ArrayList<Integer> busroutelist = new ArrayList<Integer>();
	java.util.Hashtable<Integer, downloaderBusStop> allBusStop = new java.util.Hashtable<Integer, downloaderBusStop>();

	java.util.Hashtable<Integer, downloaderBusRoute> allBusRoute = new java.util.Hashtable<Integer, downloaderBusRoute>();

	// ==============================

	private void getListOfRoute() {

		try {
			URLConnection busListConnection;
			URL busList = new URL(URL_BUSMAP);

			busListConnection = busList.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					busListConnection.getInputStream()));

			String inputLine, inputLine2;
			String[] info;

			while ((inputLine = in.readLine()) != null) {
				if (inputLine.contains(TAG_STARTLIST))
					while ((inputLine2 = in.readLine()) != null) {
						if (inputLine2.contains(TAG_ENDLIST)
								|| inputLine2.length() <= 10)
							return;
						else {
							info = inputLine2.split("\"");
							busroutelist.add(Integer.parseInt(info[1]));
						}
					}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}

	private void getAllRoute(boolean luotdi) {
		if (busroutelist.size() == 0)
			getListOfRoute();
		String filename = "", URL_BUSROUTE;
		downloaderBusRoute busroute;

		// for each route, get info
		for (Integer routeID : busroutelist) {
			try {
				filename = FOLDERNAME + "route" + routeID;
				filename += (luotdi) ? "_luotdi.txt" : "_luotve.txt";
				URL_BUSROUTE = "http://map.ebms.vn/Server.aspx?action=GetTuyen&TuyenId="
						+ routeID;
				URL_BUSROUTE += (luotdi) ? "&LuotDi=true" : "&LuotDi=false";

				Writer out = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(filename), "UTF-8"));
				URLConnection busRouteConnection;

				URL busList = new URL(URL_BUSROUTE);

				busRouteConnection = busList.openConnection();
				BufferedReader in = new BufferedReader(new InputStreamReader(
						busRouteConnection.getInputStream(), "UTF-8"));

				String inputLine;
				String[] info;
				downloaderBusStop temp;
				CoordinateConversion conv = new CoordinateConversion();
				double[] latlgn;

				int busStopOrder = 0;
				busroute = new downloaderBusRoute(routeID, luotdi);

				while ((inputLine = in.readLine()) != null) {
					busStopOrder = 0;

					info = inputLine.split("COL");
					for (int i = 1; i < info.length; i++) {
						info[i] = info[i].replace("{", "");
						info[i] = info[i].replace("}", "");
						info[i] = info[i].replace("\"", "");
						info[i] = info[i].replace(":", "");
						info[i] = info[i].replace(",", "");
						info[i] = info[i].replace("]", "");
						String[] info2 = info[i].split("DATA");
						info2[8] = info2[8].replaceAll(" ", "");
						latlgn = conv.utm2LatLon("48 N " + info2[4] + " "
								+ info2[5]);

						temp = new downloaderBusStop(info2[1], info2[2],
								info2[3], latlgn[0], latlgn[1],
								Integer.parseInt(info2[6]));
						out.write(temp.getLine());
						out.write("\n");

						// add bus stop to all bus stop
						if (!allBusStop.containsKey(Integer.parseInt(info2[6]))) {
							allBusStop.put(Integer.parseInt(info2[6]), temp);
							if (maxBusStopID < Integer.parseInt(info2[6]))
								maxBusStopID = Integer.parseInt(info2[6]);
						}

						// add busstop to busroute
						busroute.addBusStop(busStopOrder,
								Integer.parseInt(info2[6]));
						++busStopOrder;

					}
				}

				out.close();
				if (luotdi)
					busroute.mBusRouteID = routeID;
				else
					busroute.mBusRouteID = -routeID;

				allBusRoute.put(busroute.mBusRouteID, busroute);
				System.out.println("Successfully get " + filename);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("Error occured when getting route "
						+ filename);
			}
		}

	}

	// =======================
	public void getAllRouteFromInternet() {
		// get all available route first
		this.getListOfRoute();
		getAllRoute(true);
		getAllRoute(false);

		// write all busstop: text file
		try {
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(allBusStop_filename), "UTF-8"));
			for (int i = 0; i <= maxBusStopID; i++) {
				if (allBusStop.containsKey(i)) {
					out.write(allBusStop.get(i).getLine() + "\n");
					// System.out.println(allBusStop.get(i).getLine());

				}
			}
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}

		// write all busstop: binary file
		try {
			downloaderBusStop temp;
			DataOutputStream out = new DataOutputStream(new FileOutputStream(
					allBusStop_binfilename));
			for (int i = 0; i <= maxBusStopID; i++) {
				if (allBusStop.containsKey(i)) {
					// out.write(allBusStop.get(i).getLine() + "\n");
					temp = allBusStop.get(i);
					out.writeUTF(temp.mStreetNo);// out.writeChar('\t');
					out.writeUTF(temp.mStreetName);// out.writeChar('\t');
					out.writeUTF(temp.mDistrict);// out.writeChar('\t');
					out.writeChar(temp.mID);// out.writeChar('\t');
					out.writeDouble(temp.mLat);// out.writeChar('\t');
					out.writeDouble(temp.mLng);// out.writeChar('\t');
					// out.writeChar('\n');
				}
			}
			out.close();

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// write all busroute: text file
		try {
			// TODO: check this
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(allBusRoute_filename), "UTF-8"));
			for (int i = 0; i < 1000; i++) {
				if (allBusRoute.containsKey(i)) {
					out.write(allBusRoute.get(i).getInfo() + "\n");
				}

				if (allBusRoute.containsKey(-i)) {
					out.write(allBusRoute.get(-i).getInfo() + "\n");
				}
			}
			out.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// write all busroute: binary file
		try {
			downloaderBusRoute temp;
			DataOutputStream out = new DataOutputStream(new FileOutputStream(
					allBusRoute_binfilename));

			for (int i = 0; i < 1000; i++) {
				if (allBusRoute.containsKey(i)) {
					// TODO: try write SHORT
					temp = allBusRoute.get(i);
					out.writeShort(temp.mBusRouteID);
					for (Integer j : temp.mBusStopList) {
						if (j != 0)
							out.writeChar(j);
					}
					out.writeChar('\n');
				}

				if (allBusRoute.containsKey(-i)) {
					temp = allBusRoute.get(-i);
					out.writeShort(temp.mBusRouteID);
					for (Integer j : temp.mBusStopList) {
						if (j != 0)
							out.writeChar(j);
					}
					out.writeChar('\n');

				}
			}
			out.close();

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	public void getAllRouteFromFile() {
		try {
			downloaderBusStop temp = new downloaderBusStop();
			DataInputStream in = new DataInputStream(new FileInputStream(
					allBusStop_binfilename));
			while (true) {
				try {
					temp.mStreetNo = in.readUTF();// in.readChar();
					temp.mStreetName = in.readUTF();// in.readChar();
					temp.mDistrict = in.readUTF();// in.readChar();
					temp.mID = in.readInt();// in.readChar();
					temp.mLat = in.readDouble();// in.readChar();
					temp.mLng = in.readDouble();// in.readChar();
					System.out.println(temp.getLine());
				} catch (Exception e) {
					break;
				}
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			downloaderBusRoute temp = new downloaderBusRoute(0, true);
			DataInputStream in = new DataInputStream(new FileInputStream(
					allBusRoute_binfilename));
			Short a;


			while (true) {
				try {
					a= in.readShort();
					System.out.println(a + " ");
					if(a=='\n')
						System.out.println("abc===" + a);
//					temp.mStreetNo = in.readUTF();// in.readChar();
//					temp.mStreetName = in.readUTF();// in.readChar();
//					temp.mDistrict = in.readUTF();// in.readChar();
//					temp.mID = in.readInt();// in.readChar();
//					temp.mLat = in.readDouble();// in.readChar();
//					temp.mLng = in.readDouble();// in.readChar();
//					System.out.println(temp.getLine());
				} catch (Exception e) {
					break;
				}
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		

	}

}
